import axios, { AxiosError } from 'axios'
import type { AxiosInstance } from 'axios' 

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3001'

// 统一响应格式
interface ApiResponse<T = any> {
  code: number
  message: string
  data: T | null
}

// 获取 token
const getToken = (): string | null => {
  return localStorage.getItem('token')
}

// 创建 axios 实例
const axiosInstance: AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器 - 添加 token
axiosInstance.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 统一处理响应
axiosInstance.interceptors.response.use(
  (response) => {
    const data: ApiResponse = response.data
    if (data.code !== 200) {
      throw new Error(data.message || '请求失败')
    }
    return response
  },
  (error: AxiosError) => {
    if (error.response) {
      // 服务器返回了错误状态码
      const data = error.response.data as ApiResponse
      throw new Error(data?.message || `HTTP error! status: ${error.response.status}`)
    } else if (error.request) {
      // 请求已发出但没有收到响应
      throw new Error('网络错误，请检查网络连接')
    } else {
      // 其他错误
      throw new Error(error.message || '请求失败')
    }
  }
)

// 登录接口
export const loginApi = async (credentials: {
  username: string
  password: string
  captcha: string
}): Promise<ApiResponse<{ token: string; user: any }>> => {
  const response = await axiosInstance.post<ApiResponse<{ token: string; user: any }>>(
    '/api/auth/login',
    credentials
  )
  return response.data
}

// 获取当前用户信息
export const getCurrentUserApi = async (): Promise<ApiResponse<{ user: any }>> => {
  const response = await axiosInstance.get<ApiResponse<{ user: any }>>('/api/auth/me')
  return response.data
}

// 健康检查
export const healthCheckApi = async (): Promise<ApiResponse> => {
  const response = await axiosInstance.get<ApiResponse>('/health')
  return response.data
}

// 视频数据类型
export interface VideoItem {
  id: string
  title: string
  thumbnail: string
  videoUrl: string
  duration?: string
  description?: string
  views?: number
  uploadDate?: string
}

// 获取视频列表
export const getVideosApi = async (): Promise<ApiResponse<VideoItem[]>> => {
  const response = await axiosInstance.get<ApiResponse<VideoItem[]>>('/api/videos')
  return response.data
}

// 根据 ID 获取视频详情
export const getVideoByIdApi = async (id: string): Promise<ApiResponse<VideoItem>> => {
  const response = await axiosInstance.get<ApiResponse<VideoItem>>(`/api/videos/${id}`)
  return response.data
}

